package com.cy.detectsys.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cy.detectsys.entity.DataCenterInfo;
import com.cy.detectsys.entity.IpNetCloudServiceInfo;
import com.cy.detectsys.entity.ProbeResult;
import com.cy.detectsys.entity.ProbeResultConnectCloud;
import com.cy.detectsys.entity.vo.DataCenterInfoVo;
import com.cy.detectsys.entity.vo.ProbeResultConnectCloudVo;
import com.cy.detectsys.entity.vo.ProdeDataVo;
import com.cy.detectsys.mapper.IpNetCloudServiceInfoMapper;
import com.cy.detectsys.mapper.ProbeResultConnectCloudMapper;
import com.cy.detectsys.mapper.ProbeResultMapper;
import com.cy.detectsys.response.DataCenterDetailsResponse;
import com.cy.detectsys.response.ProbeDataResponse;
import com.cy.detectsys.response.ProbeResultConnectCloudResponse;
import com.cy.detectsys.service.DataCenterInfoService;
import com.cy.detectsys.mapper.DataCenterInfoMapper;
import com.cy.detectsys.service.IpNetCloudServiceInfoService;
import com.cy.detectsys.service.ProbeResultConnectCloudService;
import com.cy.detectsys.service.ProbeResultService;
import com.cy.detectsys.util.BaseResponseInfo;
import com.cy.detectsys.util.R;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;

import javax.xml.crypto.Data;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author asus
* @description 针对表【data_center_info】的数据库操作Service实现
* @createDate 2024-06-12 15:48:39
*/
@Service
public class DataCenterInfoServiceImpl extends ServiceImpl<DataCenterInfoMapper, DataCenterInfo>
    implements DataCenterInfoService {

    @Resource
    private DataCenterInfoMapper dataCenterInfoMapper;

    @Resource
    private ProbeResultConnectCloudMapper probeResultConnectCloudMapper;
    @Resource
    private ProbeResultMapper probeResultMapper;
    @Resource
    private ProbeResultService probeResultService;
    @Resource
    private IpNetCloudServiceInfoMapper ipNetCloudServiceInfoMapper;
    @Resource
    private  IpNetCloudServiceInfoService ipNetCloudServiceInfoService;


    @Override
    public List<Map> countAsset() {

        List<Map> maps = dataCenterInfoMapper.countAsset();
        return maps;
    }

    @Override
    public BaseResponseInfo getDataCenterList(DataCenterInfoVo dataCenterInfoVo) {
        List<DataCenterInfo> list;
        PageInfo<DataCenterInfo> dataCenterInfoPageInfo;
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        if (dataCenterInfoVo.getPageNum() != null && dataCenterInfoVo.getPageSize() != null) {
            // 分页查询
            PageHelper.startPage(dataCenterInfoVo.getPageNum(), dataCenterInfoVo.getPageSize());
            QueryWrapper<DataCenterInfo> wrapper = new QueryWrapper<>();
            // 查询国家条件
            if (StringUtils.isNotBlank(dataCenterInfoVo.getCountry())) {
                wrapper.eq("country", dataCenterInfoVo.getCountry());
            }
            // 查询可用地区条件
            if (StringUtils.isNotBlank(dataCenterInfoVo.getAvailableAreas())) {
                wrapper.eq("available_areas", dataCenterInfoVo.getAvailableAreas());
            }
            // 查询位置条件
            if (StringUtils.isNotBlank(dataCenterInfoVo.getLocation())) {
                wrapper.like("location", dataCenterInfoVo.getLocation());
            }
            // 执行条件查询
            list = list(wrapper);
            dataCenterInfoPageInfo = new PageInfo<>(list);
            baseResponseInfo.data = dataCenterInfoPageInfo;
        } else {
            // 不传分页参数时直接查询列表
            baseResponseInfo.data = list();
        }
        baseResponseInfo.setCode(200);
        baseResponseInfo.setMsg("成功");
        return baseResponseInfo;
    }

    @Override
    public BaseResponseInfo getDataCenterXContryBox() {
        QueryWrapper<DataCenterInfo> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT country");
        List<DataCenterInfo> list = dataCenterInfoMapper.selectList(wrapper);
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = list;
        baseResponseInfo.setCode(200);
        baseResponseInfo.setMsg("成功");

        return baseResponseInfo;
    }

    @Override
    public BaseResponseInfo getDataCenterIpList(ProbeResultConnectCloudVo probeResultConnectCloudVo) {
        List<IpNetCloudServiceInfo> ipNetCloudServiceInfoList;
        PageInfo<IpNetCloudServiceInfo> pageInfo;
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        ProbeResultConnectCloudResponse response = new ProbeResultConnectCloudResponse();

        if (probeResultConnectCloudVo.getPageNum() != null && probeResultConnectCloudVo.getPageSize() != null) {
            // 分页查询
            PageHelper.startPage(probeResultConnectCloudVo.getPageNum(), probeResultConnectCloudVo.getPageSize());
            QueryWrapper<IpNetCloudServiceInfo> queryWrapper = new QueryWrapper<>();

            if (probeResultConnectCloudVo!= null && StringUtils.isNotBlank(probeResultConnectCloudVo.getDataCenterName())) {
                queryWrapper.eq("data_center_name", probeResultConnectCloudVo.getDataCenterName());
            }
            if (probeResultConnectCloudVo!= null && StringUtils.isNotBlank(probeResultConnectCloudVo.getCloudService())) {
                queryWrapper.eq("cloud_service", probeResultConnectCloudVo.getCloudService());
            }
            ipNetCloudServiceInfoList = ipNetCloudServiceInfoMapper.selectList(queryWrapper);
            pageInfo = new PageInfo<>(ipNetCloudServiceInfoList);
            //response.setPageInfo(pageInfo);
            baseResponseInfo.data = pageInfo;
        } else {
            // 不传分页参数时直接查询列表
            ipNetCloudServiceInfoList = ipNetCloudServiceInfoService.list();
            baseResponseInfo.data = ipNetCloudServiceInfoList;

        }
        baseResponseInfo.setCode(200);
        baseResponseInfo.setMsg("成功");
        return baseResponseInfo;
    }

    @Override
    public BaseResponseInfo getDataCenterIpListBox() {
        //数据中心名称下拉框
        QueryWrapper<IpNetCloudServiceInfo> dataCenterWrapper = new QueryWrapper<>();
        dataCenterWrapper.select("DISTINCT data_center_name");
        List<IpNetCloudServiceInfo> dataCenterName = ipNetCloudServiceInfoMapper.selectList(dataCenterWrapper);

        QueryWrapper<IpNetCloudServiceInfo> cloudServiceWrapper = new QueryWrapper<>();
        cloudServiceWrapper.select("DISTINCT cloud_service");
        List<IpNetCloudServiceInfo> cloudService = ipNetCloudServiceInfoMapper.selectList(cloudServiceWrapper);

        List<IpNetCloudServiceInfo> filteredDataCenterName = new ArrayList<>();
        List<IpNetCloudServiceInfo> filteredCloudService = new ArrayList<>();

        for (IpNetCloudServiceInfo item : dataCenterName) {
            String dataCenter = item.getDataCenterName();
            if (StringUtils.isNotBlank(dataCenter)) {
                filteredDataCenterName.add(item);
            }
        }

        for (IpNetCloudServiceInfo item : cloudService) {
            String cloud = item.getCloudService();
            if (StringUtils.isNotBlank(cloud)) {
                filteredCloudService.add(item);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("dataCenterName", filteredDataCenterName);
        map.put("cloudService", filteredCloudService);

        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = map;
        baseResponseInfo.setCode(200);
        baseResponseInfo.setMsg("成功");
        return baseResponseInfo;
    }

    @Override
    public BaseResponseInfo assetProbeDataList(ProdeDataVo prodeDataVo) {
        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        Map<String, Object> map = new HashMap<>();
        if (prodeDataVo.getPageNum() != null && prodeDataVo.getPageSize() != null) {
            List<ProbeResult> probeResults = probeResultService.assetProbeDataList(prodeDataVo);
            //遍历probeResults
            for (ProbeResult probeResult : probeResults) {
               // List<Map<String, Object>> resultDetails = new ArrayList<>();
                JSONObject resultDetails = new JSONObject();
                String matchResults = probeResult.getMatchResults();
                if (StringUtils.isNotBlank(matchResults) && matchResults!="null"){
                    try {
                        JSONArray jsonArray = JSON.parseArray(matchResults);

                        if (jsonArray!= null &&!jsonArray.isEmpty()) {
                            for (Object obj : jsonArray) {
                                JSONObject jsonObject = (JSONObject) obj;
                                // 检查 JSON 对象的键是否存在
                                if (jsonObject.containsKey("Layer") && jsonObject.containsKey("Product") && jsonObject.containsKey("Version")) {
                                    int layer = jsonObject.getInteger("Layer");
                                    String product = jsonObject.getString("Product");
                                    String version = jsonObject.getString("Version");

                                    String productLayer = null;
                                    if (StringUtils.isNotBlank(version)) {
                                        productLayer = product + "-" + version;
                                    } else {
                                        productLayer = product;
                                    }
                                    JSONArray array = new JSONArray();
                                    array.add(productLayer);

                                    if (layer == 4) {
                                        resultDetails.put("应用软件层", array);
                                    }
                                    if (layer == 3) {
                                        resultDetails.put("框架层",array);
                                    }
                                    if (layer == 2) {
                                        resultDetails.put("操作系统",array);
                                    }

                                    System.out.println(product + "-" + version);
                                } else {
                                    // 如果 JSON 对象缺少必要的键，处理错误情况
                                    // 可以打印错误信息或采取其他适当的措施
                                }
                            }
                        } else {
                            // 如果解析后的数组为空，处理错误情况
                            // 可以打印错误信息或采取其他适当的措施
                        }
                    } catch (JSONException e) {
                        // 如果解析过程中发生 JSONException 异常，说明 matchResults 不符合 JSON 格式
                        // 可以打印错误信息或采取其他适当的措施
                    }

                }
                probeResult.setResultDetails(resultDetails);
            }
            //查询总数 total
//            QueryWrapper<ProbeResult> wrapper = new QueryWrapper<>();
//            int total = (int) (long) probeResultMapper.selectCount(wrapper);
            int total = probeResults.size();
            map.put("total",total);
            map.put("probeResults",probeResults);
            baseResponseInfo.data = map;
        }
        baseResponseInfo.setCode(200);
        baseResponseInfo.setMsg("成功");
        return baseResponseInfo;
    }



    @Override
    public BaseResponseInfo getDataCenterXPortBox() {
        QueryWrapper<ProbeResult> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT port");
        List<ProbeResult> portList = probeResultMapper.selectList(wrapper);

        QueryWrapper<DataCenterInfo> dataCenterWrapper = new QueryWrapper<>();
        dataCenterWrapper.select("DISTINCT data_center_name");
        List<DataCenterInfo> dataCenterName = dataCenterInfoMapper.selectList(dataCenterWrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("portList", portList);
        map.put("dataCenterName", dataCenterName);

        BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
        baseResponseInfo.data = map;
        baseResponseInfo.setCode(200);
        baseResponseInfo.setMsg("成功");

        return baseResponseInfo;
    }




    @Override
      public BaseResponseInfo getDataCenterXAvailableAreasBox () {
                QueryWrapper<DataCenterInfo> wrapper = new QueryWrapper<>();
                wrapper.select("DISTINCT available_areas");
                List<DataCenterInfo> list = dataCenterInfoMapper.selectList(wrapper);
                BaseResponseInfo baseResponseInfo = new BaseResponseInfo();
                baseResponseInfo.data = list;
                baseResponseInfo.setCode(200);
                baseResponseInfo.setMsg("成功");

                return baseResponseInfo;
            }


}


